package AnswerOfComent;

import structure.ListNode;

/**
 * 旋转链表
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 */
public class Tencent_61_rotateRight {
    /**
     * 官方题解
     * @param head
     * @param k
     * @return
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        int add = n - k % n;
        if (add == n) {
            return head;
        }
        iter.next = head;
        while (add-- > 0) {
            iter = iter.next;
        }
        ListNode ret = iter.next;
        iter.next = null;
        return ret;
    }
    /**
     * 大神题解
     */
    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null|| k == 0)
            {
                return head;
            }
            int n = 0;			   //链表的长度
            ListNode tail = null;  //尾节点
            for(ListNode p = head; p != null ; p = p.next){
                tail = p;
                n++;
            }
            k %= n;
            ListNode p = head;
            for(int i = 0; i < n - k - 1; i++)  p = p.next;   //找到链表的第n-k个节点
            tail.next = head;
            head = p.next;
            p.next = null;
            return head;  //返回新的头节点
        }
    }

}
